/*************************************************************************
 * File Name:    ZigZag_Conversion.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/6 23:20:20
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: ZigZag Conversion
 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number
 | of rows like this: (you may want to display this pattern in a fixed font for better legibility)
 |
 | P   A   H   N
 | A P L S I I G
 | Y   I   R
 | And then read line by line: "PAHNAPLSIIGYIR"
 | Write the code that will take a string and make this conversion given a number of rows:
 |
 | string convert(string text, int nRows);
 | convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

class Solution
{
public:
    string convert(string s, int nRows)
    {
        if (nRows <= 1) return s;
        
        int N = s.size();
        int L = 2 * nRows - 2;
        string ans = "";
        
        for (int i = 0; i < N; i += L) {
            ans += s[i];
        }
        
        for (int i = 1; i < nRows - 1; ++i) {
            for (int j = i; j < N; j += L) {
                ans += s[j];
                if (j + L - 2 * i < N) ans += s[j + L - 2 * i];
            }
        }
        
        for (int i = nRows - 1; i < N; i += L) {
            ans += s[i];
        }
        return ans;
    }
};

